<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/params' }">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意: 只允许为第三级分类设置相关参数!" type="warning" show-icon>
      </el-alert>
      <el-row class="cate_par">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader v-model="selectedCateKeys" :options="cateList" :props="cateListProps" @change="cateIdChange">
          </el-cascader>
        </el-col>
      </el-row>
      <template>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isButtonDisabled" @click="addParams">添加参数</el-button>
            <el-table :data="manyTableDate" style="width: 100%" border>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" class="tag_params" closable
                    @close="deleteTagInput(i,scope.row)">{{ item }}</el-tag>
                  <el-input v-if="scope.row.tagInputVisible" ref="tagSaveTagInputRefs" v-model="scope.row.inputValue"
                    class="new-tag" size="small" @keyup.enter.native="tagHandleInputConfirm(scope.row)"
                    @blur="tagHandleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="tagShowInput(scope.row)">+ New Tag
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="#" type="index">
              </el-table-column>
              <el-table-column prop="attr_name" label="参数名称">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" @click="editParams(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" size="mini" @click="deleteParems(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" size="mini" :disabled="isButtonDisabled" @click="addParams">添加属性</el-button>
            <el-table :data="onlyTableDate" style="width: 100%" border>
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" class="tag_params" closable
                    @close="deleteTagInput(i,scope.row)">{{ item }}</el-tag>
                  <el-input v-if="scope.row.tagInputVisible" ref="tagSaveTagInputRefs" v-model="scope.row.inputValue"
                    class="new-tag" size="small" @keyup.enter.native="tagHandleInputConfirm(scope.row)"
                    @blur="tagHandleInputConfirm(scope.row)">
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="tagShowInput(scope.row)">+ New Tag
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="#" type="index">
              </el-table-column>
              <el-table-column prop="attr_name" label="参数名称">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" @click="editParams(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" size="mini" @click="deleteParems(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-card>
    <!-- 添加参数 -->
    <el-dialog :title="'添加'+addTitle" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px">
        <el-form-item label="addTitle：" prop="attr_name">
          <el-input v-model="addCateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数 -->
    <el-dialog :title="'添加'+addTitle" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editParamsForm" :rules="editparamsRules" ref="editParamsFormRefs" label-width="100px">
        <el-form-item label="addTitle：" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.getCateList()
  },
  data () {
    return {
      cateList: [],
      selectedCateKeys: [],
      cateListProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      manyTableDate: [],
      onlyTableDate: [],
      addCateForm: {
        attr_name: ''
      },
      addDialogVisible: false,
      addCateFormRules: {
        attr_name: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }]
      },
      editParamsForm: {
        attr_name: ''
      },
      editDialogVisible: false,
      editparamsRules: {
        attr_name: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }]
      }
    }
  },
  computed: {
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    isButtonDisabled () {
      if (this.selectedCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    addTitle () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  methods: {
    async getCateList () {
      const {
        data: res
      } = await this.$http.get('http://kb.dekunlu.top/api/private/v1/categories')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.cateList = res.data
    },
    cateIdChange () {
      this.getParamsData()
    },
    handleClick (tab, event) {
      this.getParamsData()
    },
    async getParamsData () {
      const {
        data: res
      } = await this.$http.get(`http://kb.dekunlu.top/api/private/v1/categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.tagInputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableDate = res.data
      } else {
        this.onlyTableDate = res.data
      }
    },
    addParams () {
      this.addDialogVisible = true
    },
    async addParamsCate () {
      const {
        data: res
      } = await this.$http.post(`http://kb.dekunlu.top/api/private/v1/categories/${this.cateId}/attributes`, {
        attr_name: this.addCateForm.attr_name,
        attr_sel: this.activeName
      })
      if (res.meta.status !== 201) return this.$message.error('添加分类失败')
      this.$message.success('添加分类成功')
      this.getParamsData()
      this.addDialogVisible = false
    },
    // 编辑
    async editParams (id) {
      const {
        data: res
      } = await this.$http.get(`http://kb.dekunlu.top/api/private/v1/categories/${this.cateId}/attributes/${id}`, {
        attr_name: this.editParamsForm.attr_name,
        attr_sel: this.activeName
      })
      if (res.meta.status !== 200) return this.$message.error('获取信息失败')
      this.editParamsForm = res.data
      this.getParamsData()
      this.editDialogVisible = true
    },
    editParamsCate () {
      this.$refs.editParamsFormRefs.validate(async valid => {
        if (!valid) return
        const {
          data: res
        } = await this.$http.put(
            `http://kb.dekunlu.top/api/private/v1/categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
            this.editParamsForm
        )
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改信息失败！')
        }
        this.$message.success('修改信息成功！')
        this.editDialogVisible = false
        this.getParamsData()
      })
    },
    editDialogClosed () {
      this.$refs.editParamsFormRefs.resetFields()
    },
    // 删除
    async deleteParems (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const {
        data: res
      } = await this.$http.delete(`http://kb.dekunlu.top/api/private/v1/categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getParamsData()
    },
    addDialogClosed () {
      this.$refs.addCateFormRef.resetFields()
    },
    // 标签
    tagHandleInputConfirm (scope) {
      if (scope.inputValue.trim().length === 0) {
        scope.inputValue = ''
        scope.tagInputVisible = false
        return
      }
      scope.attr_vals.push(scope.inputValue.trim())
      scope.inputValue = ''
      scope.tagInputVisible = false
      this.getTagInput(scope)
    },
    async getTagInput (scope) {
      const {
        data: res
      } = await this.$http.put(`http://kb.dekunlu.top/api/private/v1/categories/${this.cateId}/attributes/${scope.attr_id}`, {
        attr_name: scope.attr_name,
        attr_sel: scope.attr_sel,
        attr_vals: scope.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('添加数据失败')
      }
      this.$message.success('添加数据成功')
    },
    deleteTagInput (i, scope) {
      scope.attr_vals.splice(i, 1)
      this.getTagInput(scope)
    },
    tagShowInput (scope) {
      scope.tagInputVisible = true
      this.$nextTick(_ => {
        this.$refs.tagSaveTagInputRefs.$refs.input.focus()
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .cate_par {
    margin: 20px 0;
  }

  .el-table {
    margin-top: 20px;
  }

  .el-tag {
    margin-right: 5px;
  }

  .new-tag {
    width: 120px;
  }
</style>
